using System;
using System.Collections.Generic;
using ILRuntime.CLR.TypeSystem;
using ILRuntime.CLR.Method;
using Pumpkin.Utils;

namespace Pumpkin.FrameBase
{
    public class CrossDomainInfo
    {
        public string ClassName;
        public Dictionary<string, IMethod> Methods = new Dictionary<string, IMethod>();
        public IType ClassType;

        public CrossDomainInfo(string name)
        {
            ClassName = name;
            ILRTUtils.GetDomain().LoadedTypes.TryGetValue(ClassName, out ClassType);
            if (ClassType == null)
            {
                string error = string.Format("cant find {0} in dll", ClassName);
                throw new InvalidOperationException(error);
            }
        }

        public void RegisterMethods(string name, int param_num)
        {
            var method = ClassType.GetMethod(name, param_num);
            if (method == null)
            {
                string error = string.Format("cant find method{0} in class {1} in dll", name, ClassName);
                throw new InvalidOperationException(error);
            }

            Methods[name] = method;
        }
    }


    public class CrossDomainInfoFactory : Singleton<CrossDomainInfoFactory>
    {
        private static Dictionary<string, CrossDomainInfo> infos = new Dictionary<string, CrossDomainInfo>();
        public CrossDomainInfo Create(string className)
        {
            var info = infos.GetOrDefault(className);
            if (info == null)
            {
                try
                {
                    info = new CrossDomainInfo(className);
                    InitCrossInfo(info);
                }
                catch (Exception e)
                {
                    Log.LogError(className + " or its methods were not found in cross domain");
                    throw e;
                }
            }
            return info;
        }

        private void InitCrossInfo(CrossDomainInfo info)
        {
            CrossMethods.Instance.RegisterMethods(info);
        }
    }
}